// Node-RED Function Node Code - 处理hbbtst格式的MQTT数据
// Topic格式: /hbbtst/dra/{projectId}/{propId}/
// Payload格式: [{"propId":"1612610899242262528","val":"0"}]
// 通过PROJECT_DATA全局变量根据projectId查找tenantId

// 初始化全局数据存储
if (!global.get('mqttDataStore')) {
    global.set('mqttDataStore', {});
}

// 根据projectId查找tenantId
function findTenantIdByProjectId(projectId) {
    const projectData = global.get('PROJECT_DATA') || [];
    
    for (const project of projectData) {
        if (project.project_id && project.project_id.toString() === projectId.toString()) {
            return project.tenant_id.toString();
        }
    }
    
    return null;
}

// 从topic中提取projectId和propId
function extractIdsFromTopic(topic) {
    const parts = topic.split('/');
    
    if (parts.length >= 5 && parts[1] === 'hbbtst' && parts[2] === 'dra') {
        const projectId = parts[3];
        const propId = parts[4];
        
        const tenantId = findTenantIdByProjectId(projectId);
        if (!tenantId) {
            return null;
        }
        
        return {
            tenantId: tenantId,
            projectId: projectId,
            propId: propId
        };
    }
    
    return null;
}

// 保存数据到结构化存储
function saveDataToStore(tenantId, projectId, propId, value) {
    const dataStore = global.get('mqttDataStore') || {};
    
    if (!dataStore[tenantId]) {
        dataStore[tenantId] = {};
    }
    if (!dataStore[tenantId][projectId]) {
        dataStore[tenantId][projectId] = {};
    }
    
    dataStore[tenantId][projectId][propId] = {
        value: value,
        timestamp: new Date().toISOString(),
        lastUpdate: Date.now()
    };
    
    global.set('mqttDataStore', dataStore);
    
    return dataStore[tenantId][projectId];
}

// 主处理逻辑
try {
    // 获取topic和payload
    const topic = msg.topic;
    const payload = msg.payload;
    
    // 验证数据格式
    if (!topic) {
        node.error('Invalid message format: topic missing');
        return null;
    }
    
    if (!Array.isArray(payload)) {
        node.error('Invalid payload format: expected array');
        return null;
    }
    
    // 从topic中提取ID
    const ids = extractIdsFromTopic(topic);
    if (!ids) {
        node.error('Invalid topic format: cannot extract projectId and propId');
        return null;
    }
    
    const { tenantId, projectId, propId } = ids;
    
    // 处理payload中的值
    let value = null;
    if (payload.length > 0 && payload[0] && payload[0].val !== undefined) {
        value = payload[0].val;
    } else {
        return null;
    }
    
    // 保存数据
    const savedData = saveDataToStore(tenantId, projectId, propId, value);
    
    // 创建返回消息
    msg.result = {
        topic: topic,
        tenantId: tenantId,
        projectId: projectId,
        propId: propId,
        value: value,
        savedData: savedData,
        timestamp: new Date().toISOString(),
        messageCount: 1
    };
    
    return msg;
    
} catch (error) {
    node.error('Error processing MQTT data: ' + error.message);
    return null;
}
